/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.sales;

import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.math.BigDecimal;
import java.util.Date;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import main.ServicesList;
import model.sales.SalesInit;
import model.system.SystemUser;
import org.apache.log4j.Logger;
import utility.StringUtils;
import utility.com.InputValidation;
import utility.com.TextComponentUtils;
import view.DialogTemplate;

/**
 *
 * @author Lalugina
 */
public class SalesInitFrm extends DialogTemplate {

    private Object oldValue, newValue;
    private SalesInit salesInit;
    private static Logger log = Logger.getLogger(SalesInitFrm.class);
        
    public SalesInitFrm() {
        super(ServicesList.MAIN_FRAME, true);
        initComponents();
        initComponentsRules();
    }

    private void setUser(SystemUser systemUser) {
         if (systemUser != null) {
             txtUser.setText(systemUser.getUserName());
             salesInit.setUserInserted(systemUser.getUserName());
             moveNext();
        }
    }
    
    private void getUser(String kode) {
        SystemUser systemUser = ServicesList.getSystemUserService().getSystemUser(kode);
        if (systemUser != null) {setUser(systemUser); }
        else { 
            salesInit.setUserInserted("");
            JOptionPane.showMessageDialog(this, "Operator tidak terdaftar."
                ,"Warning",JOptionPane.WARNING_MESSAGE);
        }
    }

    class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_ENTER: 
                    switch (e.getComponent().getName()) {
                        case "txtUser":
                            newValue = txtUser.getText();
                            if (!newValue.equals(oldValue)) { getUser(newValue.toString()); }
                            else {moveNext();}
                            break;
                        case "txtKasir":
                            newValue = txtKasir.getText();
                            if (!newValue.equals(oldValue)) { 
                                Integer nextShift=1;
                                SalesInit init = ServicesList.getSalesInitService().getNextShift(txtKasir.getText());
                                if (init!=null) {nextShift = init.getShiftId()+1;}
                                txtShift.setText(nextShift.toString());
                                moveNext();
                            }else {moveNext();}
                            break;
                        default:
                            moveNext();
                            break;
                    }
                    
                break;            
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();}
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText(); }
            
            if (!newValue.equals(oldValue)) { initButtonState(true); }
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtDate = new javax.swing.JTextField();
        txtKasir = new javax.swing.JTextField();
        txtUser = new javax.swing.JTextField();
        txtShift = new javax.swing.JTextField();
        txtJumlah = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        btnNew = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtDate.setEditable(false);
        txtDate.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtDate.setFocusable(false);
        txtDate.setName("txtDate"); // NOI18N

        txtKasir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtKasir.setName("txtKasir"); // NOI18N

        txtUser.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtUser.setName("txtUser"); // NOI18N

        txtShift.setEditable(false);
        txtShift.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtShift.setFocusable(false);
        txtShift.setName("txtShift"); // NOI18N

        txtJumlah.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtJumlah.setName("txtJumlah"); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Tanggal :");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("No Kasir :");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Operator :");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("No Shift :");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Jumlah Modal :");

        btnSave.setText("Simpan");
        btnSave.setName("btnSave"); // NOI18N

        btnPrint.setText("Print");
        btnPrint.setName("btnPrint"); // NOI18N

        btnNew.setText("Tambah");
        btnNew.setName("btnSave"); // NOI18N

        btnClose.setText("Keluar");
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtUser)
                            .addComponent(txtKasir, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtShift, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDate, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                            .addComponent(txtJumlah)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnPrint)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnNew)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnClose)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtKasir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtShift, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtJumlah, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnClose)
                    .addComponent(btnSave)
                    .addComponent(btnPrint)
                    .addComponent(btnNew))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtDate;
    private javax.swing.JTextField txtJumlah;
    private javax.swing.JTextField txtKasir;
    private javax.swing.JTextField txtShift;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables

    @Override
    public int execute(int id) {
        return 0;
    }
    
    public long execute(long id) {
        setLocationRelativeTo(null);
        initForm();
        if (id!=0) { loadDataInit(id); }

        setVisible(true);
        if (salesInit!=null) {
        return salesInit.getId();}
        else { return 0; }
    }

    @Override
    protected void initForm() {
        salesInit = new SalesInit();
        txtDate.setText(StringUtils.formatDateTime24(new Date()));       
        txtJumlah.setText("");
        txtKasir.setText("");
        txtShift.setText("");
        txtUser.setText("");
        initButtonState(false);            
    }

    @Override
    protected void loadData(int id) {}
    
    protected void loadDataInit(long id) {
        salesInit = ServicesList.getSalesInitService().get(id);
        if (salesInit!=null) {
            
            txtDate.setText(StringUtils.formatDateTime24(salesInit.getTransDate()));       
            txtJumlah.setText(StringUtils.formatNumber(salesInit.getTunai()));
            txtKasir.setText(salesInit.getPcId());
            txtShift.setText(salesInit.getShiftId().toString());
            txtUser.setText(salesInit.getUserInserted());
        }
    }

    @Override
    protected void saveData() {
        //hanya bisa save
        if(salesInit.getId()==0) {
            salesInit.setPcId(txtKasir.getText());
            salesInit.setModal(TextComponentUtils.parseNumberToBigDecimal((String)txtJumlah.getText()));
            salesInit.setShiftId(Integer.parseInt(txtShift.getText()));
            salesInit.setPcId(txtKasir.getText());
            salesInit.setUserInserted(txtUser.getText());

            boolean saved = false;
            try{
                saved = ServicesList.getSalesInitService().save(salesInit);

            } catch(Exception ex){
                log.error(ex);
                JOptionPane.showMessageDialog(this, "Data gagal disimpan."
                ,"Error",JOptionPane.ERROR_MESSAGE);
            }
            initButtonState(!saved);
        }
    }

    @Override
    protected void validasi() {
        BigDecimal jumlah = TextComponentUtils.parseNumberToBigDecimal((String)txtJumlah.getText());
        if (InputValidation.isValid(txtKasir, !"".equals(txtKasir.getText()), "Nomor kasir belum diisi.")) {
        if (InputValidation.isValid(txtShift, !"".equals(txtShift.getText()), "Shift belum diisi.")) {
        if (InputValidation.isValid(txtUser, !"".equals(salesInit.getUserInserted()), "Operator belum diisi.")) {
        if (InputValidation.isValid(txtJumlah, jumlah.compareTo(BigDecimal.ZERO) > 1, "Operator belum diisi.")) {
            
        if (JOptionPane.showConfirmDialog(this, "Data sudah benar ?","Confirmation",JOptionPane.YES_NO_OPTION)==0) {
            saveData();
       }}}}}
    }

    @Override
    protected void moveNext() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.focusNextComponent();
    }

    @Override
    protected void initButtonState(boolean status) {
        btnSave.setEnabled(salesInit.getId() == 0 && status);
        btnPrint.setEnabled(salesInit.getId() > 0);
    }
    
    private void initComponentsRules() {
        TextComponentUtils.setNumericTextOnly(txtShift);
        TextComponentUtils.setCurrency(txtJumlah);
        
        txtJumlah.addKeyListener(new ActionKeyListener());
        txtJumlah.addFocusListener(new ActionFocusGained());
        txtKasir.addKeyListener(new ActionKeyListener());
        txtKasir.addFocusListener(new ActionFocusGained());
        txtShift.addKeyListener(new ActionKeyListener());
        txtShift.addFocusListener(new ActionFocusGained());
        txtUser.addKeyListener(new ActionKeyListener());
        txtUser.addFocusListener(new ActionFocusGained());
        
        btnClose.registerKeyboardAction(btnClose.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnClose.registerKeyboardAction(btnClose.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);

        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);

        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
    }
}
